package A一周刷爆LeetCode.A基础班.F二叉树;

import java.util.LinkedList;

/**
 * @author wei.zhao
 * @description: 二叉树的宽度优先遍历
 * @date 2022年02月18日 9:48
 */
public class Code03_WidthTraversal {

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);
        head.left.left.left = new Node(8);
        System.out.print("二叉树的宽度优先遍历：");
        widthTraversal(head);
    }

    public static void widthTraversal(Node head) {
        if (head == null) {
            return;
        }
        LinkedList<Node> queue = new LinkedList<>();
        queue.add(head);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            System.out.print(node.value + " ");
            if (null != node.left) {
                queue.add(node.left);
            }
            if (null != node.right) {
                queue.add(node.right);
            }
        }
        System.out.println();
    }

}
